package cn.cs.controller;

import cn.cs.client.AccountDetailClient;
import cn.cs.client.RestClientUserClient;
import cn.cs.common.*;
import cn.cs.pojo.ClientUser;
import cn.cs.pojo.Invoice;
import cn.cs.pojo.InvoiceTitle;
import cn.cs.service.InvoiceService;
import cn.cs.service.InvoiceTitleService;
import cn.cs.service.RepOrderService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/invoice")
public class InvoiceController {

    @Resource
    private InvoiceService invoiceService;
    @Resource
    private InvoiceTitleService invoiceTitleService;
    @Resource
    private RepOrderService repOrderService;

    @Resource
    private RestClientUserClient clientUserClient;


    /**
     * 分页查询 发票信息
     *
     * @param pageNumber
     * @param pageSize
     * @return
     * @throws Exception TODO 添加搜索
     */
    @RequestMapping(value = "/csPlatform/getInvoiceByPage")
    public Dto getClientBigUserByPage(Integer pageNumber, Integer pageSize, String userPhone, String userId) throws Exception {
        Map<String, Object> param = new HashMap<>();
        param.put("userPhone", userPhone);
        param.put("userId", userId);
        List<ClientUser> list = clientUserClient.getClientUserByLikePhone(userPhone);
        param.put("list", list);
        return DtoUtil.returnSuccess("获取成功", invoiceService.queryInvoicePageByMap(param, pageNumber, pageSize));
    }

    /**
     * 上传发票图片
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/csPlatform/uploadInvoiceImg")
    public Dto uploadInvoiceImg(HttpServletRequest request) throws Exception{
        String id = request.getParameter("id");//发票Id
        List<UploadInfo> list = UploadUtil.filesUpload(request,"order//invoice//"+id);
        for(UploadInfo info :list){
            Invoice invoice = new Invoice();
            invoice.setId(id);
            invoice.setState("1");//已开票
            invoice.setImg(request.getRequestURL().toString().replace(request.getRequestURI(),"") + "/image/order/invoice/"+ id + "/"+ info.getNewName());
            return DtoUtil.returnSuccess("上传成功", invoiceService.modifyInvoice(invoice));
        }
        return DtoUtil.returnFail("操作失败，请重试", "001");
    }

    /**
     * 单图上传
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/p/uploadImg")
    public Dto uploadImg(HttpServletRequest request) throws Exception{
        UploadInfo info = UploadUtil.filesUpload(request,"order//uploadImg//img").get(0);
        return DtoUtil.returnSuccess("上传成功", request.getRequestURL().toString().replace(request.getRequestURI(),"") + "/image/order/uploadImg/img/"+ info.getNewName());
    }

    /**
     * 发票申请发送邮件
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/csPlatform/sendInvoiceEmail")
    public Dto sendInvoiceEmail(String id, String title, String content) throws Exception{
         Invoice invoice = invoiceService.getInvoiceById(id);
        if(invoice != null){
            String img = invoice.getImg();
            if(EmptyUtils.isNotEmpty(img)){
                String email = invoice.getEmail();
                if(EmptyUtils.isNotEmpty(email)){
                    if("1".equals(invoice.getState())){
                        EmailUtil.sendEmail(email, title, content, img);//发送邮件
                        invoice.setState("2");//发票已发送邮件
                        return DtoUtil.returnSuccess("邮件发送成功", invoiceService.modifyInvoice(invoice));
                    }
                    return DtoUtil.returnFail("已发送过邮件，请勿重复发送", "002");
                }
                return DtoUtil.returnFail("此发票申请无邮箱地址", "002");
            }
            return DtoUtil.returnFail("此发票申请未上传图片", "002");
        }
        return DtoUtil.returnFail("发票申请不存在，请重试", "001");

    }


    /**
     * 发送到邮箱
     * @param title
     * @param content
     * @param img
     * @param email
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/csPlatform/sendInvoiceToEmail")
    public Dto sendInvoiceToEmail(String title, String content, String img, String email) throws Exception{
        EmailUtil.sendEmail(email, title, content, img);//发送邮件
        return DtoUtil.returnSuccess("邮件发送成功", "");
    }




    /**
     * 申请发票前获取需要开发票的订单信息
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/wxApi/getOrderInvoiceByUserId")
    public Dto getOrderInvoiceByUserId(HttpServletRequest request)throws Exception{
        return repOrderService.getOrderInvoiceByUserId(request);
    }



    /**
     * 提交发票申请
     * @param invoice
     * @return
     * @throws Exception
     */
    @PostMapping(path = "/wxApi/addInvoice")
    @Transactional
    public Dto addInvoice(@RequestBody Invoice invoice)throws Exception{
        String orderIds = invoice.getOrderIds();
        String userId = invoice.getUserId();
        if(EmptyUtils.isEmpty(userId)){
            return DtoUtil.returnFail("用户不存在，请重新授权登陆", "userNull001");
        }


        String type = invoice.getType();
        if("1".equals(type)){
            // 去修改订单状态，订单已经开发票
            repOrderService.updateOrderByIds(orderIds);
        }else if("2".equals(type)){
            // 去修改订单状态，订单已经开发票
            invoiceService.updateAccountDetailByIds(orderIds);
        }

        invoice.setId(IdWorker.getId());
//        invoice.setInvoiceNumber(IdWorker.getId());
        invoiceService.addInvoice(invoice);
        if("2".equals(invoice.getInvoiceState())){
            InvoiceTitle invoiceTitle = invoiceTitleService.getInvoiceTitleByName(invoice.getTitile(), invoice.getUserId());
            if(EmptyUtils.isNotEmpty(invoiceTitle)){
                invoiceTitle.setTaxpayerNumber(invoice.getTaxpayerNumber());
                invoiceTitle.setModifyDate(new Date());
                invoiceTitleService.modifyInvoiceTitle(invoiceTitle);
            }else{
                InvoiceTitle title = new InvoiceTitle();
                title.setName(invoice.getTitile());
                title.setTaxpayerNumber(invoice.getTaxpayerNumber());
                title.setCreateDate(new Date());
                title.setModifyDate(new Date());
                title.setIsDefault("0");
                title.setUserId(invoice.getUserId());
                invoiceTitleService.addInvoiceTitle(title);
            }
        }
        return DtoUtil.returnSuccess("操作成功", invoice.getId());
    }

    /**
     * 获取发票历史
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/wxApi/getInvoiceList")
    public Dto getInvoiceList(HttpServletRequest request, HttpServletResponse response, String userId) throws  Exception{
        response.setHeader("Access-Control-Allow-Origin", "*");

        ClientUser clientUser = clientUserClient.getClientUserById(userId);
        List<Invoice> list = invoiceService.getInvoiceListByUserId(userId, clientUser.getUserPid());
        for(Invoice a:list){
            a.setUser_name(clientUser.getUserName());
        }
        return DtoUtil.returnSuccess("查询成功", list);
    }


    /**
     * 根据picId查询发票图片
     */
    @RequestMapping("/p/getInvoicePictureByPicId/{id}")
    @ResponseBody
    public Dto getInvoicePic(@PathVariable("id") String id)throws Exception{
        Invoice invoice = invoiceService.getInvoiceById(id);
        return DtoUtil.returnSuccess("查询成功", invoice);
    }


    /**
     * 查询发票详情
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/p/getInvoiceDetails/{id}")
    public Dto getInvoiceDetails(@PathVariable("id") String id) throws  Exception{
        Invoice list = invoiceService.getInvoiceById(id);
        return DtoUtil.returnSuccess("查询成功", list);
    }

    /**
     * 修改发票邮箱
     * @param id
     * @param email
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/p/updateInvoiceEmail")
    public Dto updateInvoiceEmail(String id, String email) throws  Exception{
        Invoice invoice = new Invoice();
        invoice.setId(id);
        invoice.setEmail(email);
        invoiceService.modifyInvoice(invoice);
        return DtoUtil.returnSuccess("操作成功");
    }


    /**
     * 修改发票号码
     * @param id
     * @param invoiceNumber
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/p/updateInvoiceNumber")
    public Dto updateInvoiceNumber(String id, String invoiceNumber) throws  Exception{
        Invoice invoice = new Invoice();
        invoice.setId(id);
        invoice.setInvoiceNumber(invoiceNumber);
        invoiceService.modifyInvoice(invoice);
        return DtoUtil.returnSuccess("操作成功");
    }



    /**
     * 申请发票前获取需要开发票的订单信息  电器厂pc
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/dqcApi/getOrderInvoice")
    public Dto getOrderInvoice(HttpServletRequest request)throws Exception{
        return repOrderService.getOrderInvoiceByUserPId(request);
    }

    /**
     * 提交发票申请   电器厂pc
     * @param invoice
     * @return
     * @throws Exception
     */
    @PostMapping(path = "/dqcApi/addDQCInvoice")
    @Transactional
    public Dto addDQCInvoice(@RequestBody Invoice invoice)throws Exception{
        String orderIds = invoice.getOrderIds();

        String type = invoice.getType();
        if("1".equals(type)){
            // 去修改订单状态，订单已经开发票
            repOrderService.updateOrderByIds(orderIds);
        }else if("2".equals(type)){
            // 去修改订单状态，订单已经开发票
            invoiceService.updateAccountDetailByIds(orderIds);
        }

        invoice.setId(IdWorker.getId());
//        invoice.setInvoiceNumber(IdWorker.getId());
        invoiceService.addInvoice(invoice);
        if("2".equals(invoice.getInvoiceState())){
            InvoiceTitle invoiceTitle = invoiceTitleService.getInvoiceTitleByName(invoice.getTitile(), invoice.getUserId());
            if(EmptyUtils.isNotEmpty(invoiceTitle)){
                invoiceTitle.setTaxpayerNumber(invoice.getTaxpayerNumber());
                invoiceTitle.setModifyDate(new Date());
                invoiceTitleService.modifyInvoiceTitle(invoiceTitle);
            }else{
                InvoiceTitle title = new InvoiceTitle();
                title.setName(invoice.getTitile());
                title.setTaxpayerNumber(invoice.getTaxpayerNumber());
                title.setCreateDate(new Date());
                title.setModifyDate(new Date());
                title.setIsDefault("0");
                title.setUserId(invoice.getUserId());
                invoiceTitleService.addInvoiceTitle(title);
            }
        }
        return DtoUtil.returnSuccess("操作成功", invoice.getId());
    }


    /**
     * 获取发票历史  电器厂pc
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/dqcApi/getInvoiceListByFactoryId")
    public Dto getInvoiceListByFactoryId(HttpServletRequest request, HttpServletResponse response, String factoryId) throws  Exception{
        response.setHeader("Access-Control-Allow-Origin", "*");
        List<Invoice> list = invoiceService.getInvoiceListByUserId(factoryId, factoryId);
        return DtoUtil.returnSuccess("查询成功", list);
    }

}
